local Piece = require "packages.chess-games.nchess.core.piece"

local King = Piece:subclass("NChess.King")

function King:initialize(id)
  Piece.initialize(self, id)

  self.name = 'king'
  self.whiteStr = '王'
  self.blackStr = '王'
end

---@param board integer[][]
---@param fromX integer
---@param fromY integer
---@param x integer
---@param y integer
function King:canMoveTo(board, fromX, fromY, x, y)
  local Ch = require "packages.chess-games.nchess"
  local room = Fk:currentRoom() --[[@as NChess.RoomBase]]
  local dx = x - fromX
  local dy = y - fromY
  local targetId = board[y][x]
  local myColor = self:getColor()

  local beenChecked = false
  for Y, arrX in ipairs(board) do
    for X, id in ipairs(arrX) do
      if id ~= Ch.wK and id ~= Ch.bK and id ~= 0 then
        local p = Ch:getPieceById(id)
        if p:getColor() ~= myColor and (p:canMoveTo(board, X, Y, fromX, fromY) or p:canMoveTo(board, X, Y, (fromX + x) // 2, (fromY + y) // 2)) then
          beenChecked = true
          break
        end
      end
    end
  end

  --王车易位
  if not room:beenMoved(self.id) and not beenChecked then
    if myColor == "white" then
      local rook1, rook2 = Ch.wR1, Ch.wR2
      if y == 8 and x == 3 and not room:beenMoved(rook1) and
        board[8][2] == 0 and board[8][3] == 0 and board[8][4] == 0 then
          return true, { "castling", x, y }
      elseif y == 8 and x == 7 and not room:beenMoved(rook2) and
        board[8][6] == 0 and board[8][7] == 0 then
          return true, { "castling", x, y }
      end
    else
      local rook1, rook2 = Ch.bR1, Ch.bR2
      if y == 1 and x == 3 and not room:beenMoved(rook1) and
        board[1][2] == 0 and board[1][3] == 0 and board[1][4] == 0 then
          return true, { "castling", x, y }
      elseif y == 1 and x == 7 and not room:beenMoved(rook2) and
        board[1][6] == 0 and board[1][7] == 0 then
          return true, { "castling", x, y }
      end
    end
  end

  -- 必须周围走一步
  if math.abs(dx) > 1 or math.abs(dy) > 1 then
    return false
  end

  -- 目标位置若有己方棋子，不可走
  if targetId ~= 0 then
    local targetColor = (targetId > 0) and "white" or "black"
    if myColor == targetColor then
      return false
    end
  end

  return true
end

return King

